//
//  CDHomeViewController.m
//  CuriosityDaily
//
//  Created by JSY on 16/9/22.
//  Copyright © 2016年 theBestTeam. All rights reserved.
//

#define MoreButtonHW 44
#define leftMargin 24
#define bottomMargin 28

#import "CDHomeViewController.h"
#import "CDMoreViewController.h"
#import "CDNavigationController.h"
#import "CuriosityDaily3-swift.h"
#import "HomeTableViewModel.h"
#import "HomeWebController.h"
#import "HomeTwoTableViewCell.h"
#import "HomeThreeTableViewCell.h"
#import "HomeTableViewCell.h"
#import "WDW3D_Animation.h"

#import "CDColumnCenterController.h"
#import "SDCycleScrollView.h"


@interface CDHomeViewController ()<UITableViewDelegate,UIScrollViewDelegate,BreakOutToRefreshDelegate,UITableViewDataSource,SDCycleScrollViewDelegate>
//@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,weak) UIButton *moreButton;
@property (nonatomic, strong) BreakOutToRefreshView *refreshView;
@property(nonatomic,strong)NSArray <HomeTableViewModel *>*LBModels;
@property(nonatomic,strong)WDW3D_Animation *Animation;
@property(nonatomic,strong)NSMutableArray *Models;
@property(nonatomic,strong)UITableView *table;
@property(nonatomic,strong)HomeWebController *WebController;
@property (nonatomic,copy) NSString *lastKey;
@property (nonatomic,assign) BOOL isLoading;
@property (nonatomic,assign) CGFloat beginPointY;
@end

@implementation CDHomeViewController
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
}
-(NSArray *)Models
{
    if (!_Models)
    {
        _Models = [NSMutableArray array];
    }
    return  _Models;
}

- (void)viewDidLoad {
    [super viewDidLoad];
//    self.navigationController.navigationBar.hidden = YES;
    self.isLoading = NO;
    [self tableView];
    [self setupUI];
    [self LoadData:nil];
    [self addTestButtons];
    self.navigationItem.hidesBackButton = YES;
    [self setRefresh];
    
}
//添加测试按钮
-(void)addTestButtons{
    [self addTestButton:@"1" index:0];
    [self addTestButton:@"2" index:1];
    [self addTestButton:@"3" index:2];
    [self addTestButton:@"4" index:3];
    [self addTestButton:@"5" index:4];
    [self addTestButton:@"6" index:5];
}
//测试按钮创建方法
-(void)addTestButton:(NSString *)title index:(NSInteger)index{
    CGFloat buttonW = (CDScreen.size.width - 78) / 6;
    
    UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
    
    button1.tag = index + 1;
    
    [button1 setTitle:title forState:UIControlStateNormal];
    
    [button1 addTarget:self action:@selector(testButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    
    button1.frame = CGRectMake(78 + index * buttonW ,CDScreen.size.height - bottomMargin - 40 , buttonW - 10, 22);
    
    [button1 setBackgroundColor:[UIColor redColor]];
    [self.view addSubview:button1];
}
//测试按钮点击
-(void)testButtonClick:(UIButton *)sender{
    NSString *className = [NSString stringWithFormat:@"CDTestViewController%zd",sender.tag];
    
     UIViewController *vc = [[NSClassFromString(className) alloc] init];
    
    if (sender.tag == 2) {
        CDColumnCenterController *cvc = [[CDColumnCenterController alloc] init];
        [self.navigationController pushViewController:cvc animated:YES];
        return;
    }
    
    if (sender.tag == 6 ) {
        [self.navigationController pushViewController:vc animated:YES];
        return;
    }
    
    if (sender.tag == 5) {
        [self.navigationController pushViewController:vc animated:YES];
        return ;
    }
    
    if (sender.tag == 4) {
        [self.navigationController pushViewController:vc animated:YES];
        return;
    }
//    [self presentViewController:nav animated:YES completion:nil];
    
}

-(void)setupUI{
    //tableView
    [self addMoreButton];
}
//添加更多按钮
-(void)addMoreButton{
    UIButton *moreButton = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [moreButton setBackgroundImage:[UIImage imageNamed:@"Home@iPadPro_Yellow"] forState:UIControlStateNormal];
    [moreButton setBackgroundColor:[UIColor blackColor]];

    moreButton.layer.cornerRadius = 22;
    moreButton.layer.masksToBounds = YES;
    
    moreButton.frame = CGRectMake(leftMargin, CDScreen.size.height, MoreButtonHW, MoreButtonHW);
    
    [moreButton addTarget:self action:@selector(moreButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:moreButton];
    
    self.moreButton = moreButton;
    
    [self popAnimationWithToCenterY:CDScreen.size.height - bottomMargin - MoreButtonHW*.5];
}
//pop动画
-(void)popAnimationWithToCenterY:(CGFloat)centerY{
    POPSpringAnimation *anim = [POPSpringAnimation animationWithPropertyNamed:kPOPViewCenter];
    
    anim.toValue = [NSValue valueWithCGPoint:CGPointMake(leftMargin + MoreButtonHW*.5, centerY)];
    
    anim.springBounciness = 12;
    anim.springSpeed = 10;
//    anim?.beginTime = CACurrentMediaTime() + Double(index) * 0.025
    anim.beginTime = CACurrentMediaTime();
    
    [self.moreButton pop_addAnimation:anim forKey:nil];
}
//更多按钮点击
-(void)moreButtonClick:(UIButton *)sender{
    [self popAnimationWithToCenterY:(CDScreen.size.height + MoreButtonHW * 0.5)];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        CDMoreViewController *moreVC = [[CDMoreViewController alloc] init];
        moreVC.dismissBlock = ^{
            [self popAnimationWithToCenterY:CDScreen.size.height - bottomMargin - MoreButtonHW*.5];
        };
        moreVC.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        [self presentViewController:moreVC animated:NO completion:nil];
    });
}

#pragma mark -- 下拉刷新小游戏
-(void)setRefresh{
    
    BreakOutToRefreshView *refreshView = [[BreakOutToRefreshView alloc] initWithScrollView:self.table];
    self.refreshView = refreshView;
    self.refreshView.delegate = self;
    
    // configure the colors of the refresh view
    self.refreshView.scenebackgroundColor = [UIColor whiteColor];
    self.refreshView.paddleColor = [UIColor colorWithRed:39 green:72 blue:98];
    self.refreshView.ballColor = [UIColor colorWithRed:230 green:179 blue:61];
    self.refreshView.blockColors = @[[UIColor colorWithHue:1.0 saturation:0.9 brightness:1.0 alpha:1.0],[UIColor colorWithHue:1.0 saturation:.7 brightness:1.0 alpha:1.0], [UIColor colorWithHue:1.0 saturation:.5 brightness:1.0 alpha:1.0]];
    
//    self.refreshView.frame = CGRectMake(0, -100, CDScreen.size.width, 100);
    [self.table addSubview:self.refreshView];
    self.table.contentInset = UIEdgeInsetsMake(-20, 0, 0, 0);
}

#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    //上拉加载
    [self.refreshView scrollViewDidScroll:scrollView];
    if(((scrollView.contentOffset.y - (self.table.contentSize.height-CDScreen.size.height)) >= 0) & !self.isLoading){
        self.isLoading = YES;
//        NSString *pullUrlStr = [NSString stringWithFormat:@" http://app3.qdaily.com/app3/homes/index/%@.json",self.lastKey];
        [self loadMore];
    }
    //拖动  按钮消失和出现
    if ((scrollView.contentOffset.y - self.beginPointY) >= 100 & self.moreButton.center.y == (CDScreen.size.height - bottomMargin - MoreButtonHW*.5)) {
        [self popAnimationWithToCenterY:(CDScreen.size.height + MoreButtonHW * 0.5)];
    }else if ((scrollView.contentOffset.y - self.beginPointY) <= -100 & self.moreButton.center.y == (CDScreen.size.height + MoreButtonHW * 0.5)){
        [self popAnimationWithToCenterY:CDScreen.size.height - bottomMargin - MoreButtonHW*.5];
    }
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.refreshView scrollViewWillBeginDragging:scrollView];
    self.beginPointY = scrollView.contentOffset.y;
}

-(void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
    [self.refreshView scrollViewWillEndDragging:scrollView withVelocity:velocity targetContentOffset:targetContentOffset];
}

- (void)refreshViewDidRefresh:(BreakOutToRefreshView * __nonnull)refreshView {
    // this code is to simulage the loading from the internet
    [self LoadData:^{
        [self.refreshView endRefreshing];
    }];
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * 3), dispatch_get_main_queue(), ^{
//    });
}

#pragma mark -- penghui
-(void)tableView{
    [self.view addSubview:self.table];
    self.table.separatorStyle = UITableViewCellSelectionStyleNone;
//    self.table.tableHeaderView = [self setupADScrollView];
    /**
     *  注册cell
     */
    [self.table registerNib:[UINib nibWithNibName:@"HomeTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell"];
    [self.table registerNib:[UINib nibWithNibName:@"HomeTwoTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell2"];
    [self.table registerNib:[UINib nibWithNibName:@"HomeThreeTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell3"];
    
    //将nav改为透明
    self.navigationController.navigationBar.hidden = YES;
//    [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc]init] forBarMetrics:UIBarMetricsDefault];
//    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc]init]] ;
    
}
-(UITableView *)table{
    if (_table == nil) {
        UITableView *table = [[UITableView alloc] initWithFrame:CDScreen style:UITableViewStylePlain];
        table.delegate = self;
        table.dataSource = self;
        table.rowHeight = UITableViewAutomaticDimension;
        table.estimatedRowHeight = 400;
        table.backgroundColor = [UIColor colorWithHex:0xf3f3f3];
        CDPullToLoadView *footer = [[CDPullToLoadView alloc] init];
        footer.frame = CGRectMake(0, 0, CDScreen.size.width, 40);
        table.tableFooterView = footer;
        _table = table;
    }
    return _table;
}
//轮播器
-(WDW3D_Animation*)setupADScrollView{
    
    WDW3D_Animation *adAnimation = [[WDW3D_Animation alloc] initWithFrame:CGRectMake(0,0, self.view.frame.size.width, 303)];
    
    return adAnimation;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return self.Models.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HomeTableViewModel *model = self.Models[indexPath.item];
    if (model.type == 1)
    {
        HomeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
        cell.model = model;
        return cell;
    }else if (model.type == 2){
        HomeTwoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell2" forIndexPath:indexPath];
        cell.model = model;
        return cell;
    }
    HomeThreeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell3" forIndexPath:indexPath];
    cell.model = model;
    __weak typeof (self) weakSelf = self;
    cell.HaoQiRiBaoClick = ^(HomeTableViewModel *model){
//        weakSelf.WebController.url = model.post[@"column"][@"share"][@"url"];
//        NSLog(@"%@",model.post[@"column"][@"share"][@"url"]);
//        [weakSelf.navigationController pushViewController:self.WebController animated:YES];
    };
    return cell;
}
-(void)LoadData:(void(^)())completionHandler{
    self.isLoading = YES;
    NSURL *url = [NSURL URLWithString:@"http://app3.qdaily.com/app3/homes/index/0.json?"];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
        //         NSLog(@"%@",result);
        
        NSArray *arr = result[@"response"][@"feeds"];
        self.lastKey = result[@"response"][@"last_key"];
        NSArray *tempArray = [NSArray yy_modelArrayWithClass:[HomeTableViewModel class] json:arr];
        //         NSLog(@"%@",tempArray);
        self.Models = tempArray;
        //轮播器数据
        [self LBDaTa:result];
        if (completionHandler != nil) {
            completionHandler();
        }
        
        self.isLoading = NO;
        [self.table reloadData];
    }];
    
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    HomeTableViewModel *model = self.Models[indexPath.item];
    if (model.type != 0)
    {
        self.WebController.url = model.post[@"appview"];
        [self.navigationController pushViewController:self.WebController animated:YES];
    }
}

-(HomeWebController *)WebController
{
    if (!_WebController)
    {
        _WebController = [[HomeWebController alloc]init];
    }
    return _WebController;
}

-(void)loadMore{
    NSURL *url = [[NSURL alloc] initWithString:[NSString stringWithFormat:@"http://app3.qdaily.com/app3/homes/index/%@.json",self.lastKey]];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
        //         NSLog(@"%@",result);
        
        NSArray *arr = result[@"response"][@"feeds"];
        self.lastKey = result[@"response"][@"last_key"];
        NSArray *tempArray = [NSArray yy_modelArrayWithClass:[HomeTableViewModel class] json:arr];
        //         NSLog(@"%@",tempArray);
        for (NSInteger i = 0; i<tempArray.count; i++) {
            [self.Models addObject:tempArray[i]];
        }
        [self.table reloadData];
        self.isLoading = NO;
    }];

}
-(void)LBDaTa:(NSDictionary *)result{

    NSArray *arr1 = result[@"response"][@"banners"];
    NSLog(@"%@",arr1);
    NSArray *tempArray1 = [NSArray yy_modelArrayWithClass:[HomeTableViewModel class] json:arr1];
    //        NSLog(@"%@",tempArray1);
    self.LBModels  =tempArray1;
    NSArray *imagesURLStrings = @[
                                  self.LBModels[0].image,
                                  self.LBModels[1].image,
                                  self.LBModels[2].image
                                  ];
    NSArray *titles = @[self.LBModels[0].post[@"title"],
                        self.LBModels[1].post[@"title"],
                        self.LBModels[2].post[@"title"]
                        ];
    SDCycleScrollView *cycleScrollView2 = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 300) delegate:self placeholderImage:[UIImage imageNamed:@"placeholder"]];
    cycleScrollView2.pageControlAliment = SDCycleScrollViewPageContolAlimentCenter;
    cycleScrollView2.titlesGroup = titles;
    cycleScrollView2.titleLabelHeight = 150;
    cycleScrollView2.titleLabelBackgroundColor = [UIColor clearColor];
    cycleScrollView2.currentPageDotColor = [UIColor whiteColor];
    cycleScrollView2.titleLabelTextFont = [UIFont boldSystemFontOfSize:22];
    cycleScrollView2.currentPageDotColor = [UIColor yellowColor];
    UIView *HeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 305)];
    HeaderView.backgroundColor = [UIColor colorWithHex:0xf3f3f3];
    [HeaderView addSubview:cycleScrollView2];
    self.table.tableHeaderView = HeaderView;
    //         --- 模拟加载延迟
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        cycleScrollView2.imageURLStringsGroup = imagesURLStrings;
    });
}
//点击轮播器的代理方法
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    NSLog(@"%@", self.LBModels[index].post[@"appview"]);
    self.WebController.url = self.LBModels[index].post[@"appview"];
    [self.navigationController pushViewController:self.WebController animated:YES];}

@end
